package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.wemedia.entity.WmUser;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author LX
 * @since 2022-06-20
 */
@Slf4j
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Override
    public Integer saveWmUser(WmUserDto dto) {
        //根据apUserId 查询自媒体用户
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId, dto.getApUserId());
        WmUser wmUser = getOne(queryWrapper);
        //如果不存在就新增
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(dto.getApUserId());
            wmUser.setStatus(dto.getStatus());
            wmUser.setCreatedTime(new Date());
        }
        //如果存在就更新

        wmUser.setName(dto.getName());
        wmUser.setPhone(dto.getPhone());
        wmUser.setPassword(dto.getPassword());

        //新增或更新操作
        boolean b = saveOrUpdate(wmUser);
        if (!b) {
            log.error("新增或更新失败,apUserId={}", dto.getApUserId());
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        return wmUser.getId();
    }

}
